<template>
  <el-container>
    <SiteTree style="position: fixed" @on-choose-region="filetrStation" />
    <el-main class="warningListtContent">
      <div class="default-main ba-table-box">
        <TableHeader
          :buttons="['refresh', 'edit', 'comSearch', 'columnDisplay']"
          :quick-search-placeholder="placeholder"
          @action="baTable.onTableHeaderAction"
        />
        <!-- 表格 -->
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <Table ref="tableRef" @action="baTable.onTableAction" />
        <!-- 表单 -->
        <PopupForm ref="formRef" v-if="baTable.form.operate" />
      </div>
    </el-main>
  </el-container>
</template>
<script lang="ts" setup>
import { ref, provide, onMounted, markRaw, computed } from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff, DictOperation } from "@/utils/common"; // 导入表格api方法生成器
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import { WarningList } from "@/api/backend/index";
import PopupForm from "./popupForm.vue";
import { useRoute, useRouter } from "vue-router";
import { useNavTabs } from "@/store/navTabs";
import { useWarningLevel } from "@/store/backend/Warning/level";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { useAssetSite } from "@/store/backend/Assets/site";
import { useWarningList } from "@/store/backend/Warning/list";
import { useAssetCabinet } from "@/store/backend/Assets/cabinet";
import RGBA from "./components/rgba.vue";
import Tag from "./components/tag.vue";
import { useConfig } from "@/store/config"; //后台布局相关仓库
import TagCabinetType from "./components/cabinetType.vue";
import TagSearch from "@/components/tagSearch/index.vue";
import SiteTree from "./components/aside.vue";
import { useWarningNoticeConfig } from "@/store/backend/Warning/noticeConfig";
import Notice from "./components/noticePerson.vue";
import ReportName from "./components/reportName.vue";
import CategoryName from "./components/categoryName.vue";
import { useWarningItemObject } from "@/store/backend/Warning/itemObject";

const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const route = useRoute();
const router = useRouter();
const navTabs = useNavTabs();
const level = useWarningLevel();
const dictionary = useDictionary();
const site = useAssetSite();
const list = useWarningList();
const cabinet = useAssetCabinet();
const config = useConfig();
const noticeConfig = useWarningNoticeConfig();
const itemObject = useWarningItemObject();
const formRef = ref();

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + WarningList)
      ? (navTabs as any).pageSizeMap.get(route.path + WarningList)
      : 10;
  }
  return 10;
};

//初始化字典处理类
const dictOperation = new DictOperation();
//重写字典处理
type dictObj = (arr: any[]) => anyObj;
class NewWarningOperation extends DictOperation {
  getDictData: dictObj = (arr: any[]) => {
    let obj: any = {};
    for (let i = 0, len = arr.length; i < len; i++) {
      obj[arr[i].levelId] = arr[i].rgba;
    }
    console.log("重写字典处理", obj);
    return obj;
  };
  //重写改为获取告警级别数据列表
  getDictionary = (
    specificClass: any, //pinia仓库类
    dictText: string, //字典名称
    filed: string, //仓库存储的经过处理后的字典对象 levelId
    dictStore: string //仓库存储的原始字典数组
  ) => {
    if (
      JSON.stringify(specificClass.tags) == "{}" ||
      !(filed == "" ? true : specificClass.tags[filed]) ||
      JSON.stringify(dictionary.moreTags[dictText]) == "{}"
    ) {
      level.getWarningLevelList({ pageSize: 10000 }).then((res: any) => {
        let tempTags = this.getDictData(res);
        dictionary.moreTags[dictText] = tempTags;
        specificClass.$patch((state: any) => {
          if (filed != "") {
            state.tags[filed] = tempTags;
          }
          state[dictStore] = res;
        });
      });
    }
  };
}
const newWarningOperation = new NewWarningOperation();

//全局事件总线
const { proxy } = useCurrentInstance();
const baTable = new baTableClass(
  new baTableApi(WarningList), //this.api = api菜单管理相关
  {
    pk: "id",
    column: [
      { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("pname"),
        label: "机柜名称",
        prop: "pname",
        align: "center",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("cabinetType"),
        label: "机柜类型",
        prop: "cabinetType",
        align: "center",
        render: "customRender",
        customRender: markRaw(TagCabinetType),
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearch),
      },
      {
        show: filedShowOff("reportName"),
        label: "告警对象",
        prop: "reportName",
        align: "center",
        width: 150,
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(ReportName),
      },
      {
        show: filedShowOff("categoryName"),
        label: "告警类别",
        prop: "categoryName",
        align: "center",
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(CategoryName),
      },
      {
        show: filedShowOff("info"),
        label: "告警事件",
        prop: "info",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("state"),
        label: "告警处理状态",
        prop: "state",
        align: "center",
        render: "customRender",
        customRender: markRaw(Tag),
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearch),
      },
      {
        show: filedShowOff("levelId"),
        label: "告警级别",
        prop: "levelId",
        align: "center",
        render: "customRender",
        customRender: markRaw(RGBA),
        operator: false,
      },
      {
        show: filedShowOff("warningValue"),
        label: "告警值",
        prop: "warningValue",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("handleTime"),
        label: "处理时间",
        prop: "handleTime",
        align: "center",
        width: 155,
        operator: false,
      },
      {
        show: filedShowOff("noticePersonName"),
        label: "通知人员",
        prop: "noticePersonName",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("noticeWay"),
        label: "通知方式",
        prop: "noticeWay",
        align: "center",
        render: "customRender",
        customRender: markRaw(Notice),
        operator: false,
      },
      {
        show: filedShowOff("reportTime"),
        label: "告警时间",
        prop: "reportTime",
        align: "center",
        render: "datetime",
        width: 155,
        operator: "RANGE",
      },
      {
        show: operatorShowOff([route.path + "/edit", route.path + "/remove"]),
        label: "操作",
        align: "center",
        width: "130",
        render: "buttons",
        fixed: "right",
        operator: false,
        buttons: [
          {
            render: "tipButton",
            name: "edit",
            title: "处理",
            text: "",
            type: "primary",
            icon: "iconfont icon-pencil",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
      },
    ],
    filter: {
      pageSize: pageSizeKeep(),
    },
  },
  {
    // 默认表单数据(添加)
    defaultItems: {
      cabinetType: 0, //立式
    },
  }
);

//监控右侧宽度
const menuWidth = computed(() => config.overviewMenuWidth());

//接收站点树传递过来的数据
const filetrStation = (row: any, node: any) => {
  console.log("接收站点树传递过来的数据", row, node);
  if (node && node.checkedKeys.length !== 0) {
    baTable.comSearch.form.siteIds = node.checkedKeys;
    baTable.getList("");
  }
  if (node && node.checkedKeys.length === 0) {
    //表示取消选择直接调用刷新表单方法
    baTable.comSearch.form.siteIds = [];
    baTable.getList("");
  }
  //全选
  if (!node && row.length !== 0) {
    baTable.comSearch.form.siteIds = row;
    baTable.getList("");
  }
  //全不选
  if (!node && row.length === 0) {
    baTable.comSearch.form.siteIds = [];
    baTable.getList("");
  }
};

//获取告警对象列表
const getobjectList = () => {
  itemObject
    .getWarningItemObjectList({ pageSize: 10000 })
    .then((res: any) => {
      itemObject.fullData = res; //所有告警对象数据存储至仓库
    })
    .catch((err: any) => {});
};
getobjectList();

onMounted(() => {
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(WarningList);

  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      if (!baTable.activate) return;
      //回滚功能暂无
      if (data.name == "rollback") {
        // onRollback([data.row[baTable.table.pk!]])
      } else if (data.name == "info") {
        //携带主键字段pk
        // infoButtonClick(
        //   (data.row as TableRow)[baTable.table.pk!],
        //   data.row as any
        // );
      }
    }
  );
});

//获取字典
const getDictionary = () => {
  //获取机柜类型的字典
  dictOperation.getDictionary(
    cabinet,
    "sys_cabinet_type",
    "cabinetType",
    "type"
  );
  //获取告警级别列表将levelId与rgba颜色绑定
  newWarningOperation.getDictionary(
    list,
    "sys_arningList",
    "levelId",
    "typeLevel"
  );
  //获取告警信息处理状态字典
  dictOperation.getDictionary(list, "sys_warning_state", "state", "type");
  //获取告警通知方式的字典
  dictOperation.getDictionary(
    noticeConfig,
    "sys_warningnotice_way",
    "noticeWay",
    "typeWay"
  );
};
//获取
getDictionary();

// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("site", site);
provide("dictionary", dictionary);
provide("dictOperation", dictOperation);
provide("list", list);
provide("itemObject", itemObject);
provide("cabinet", cabinet);
provide("config", config);
provide("noticeConfig", noticeConfig);
</script>
<style lang="scss" scoped>
.el-main {
  padding: 0;
}
.default-main {
  margin: var(--ba-main-space) var(--ba-main-space) 60px var(--ba-main-space);
}
.warningListtContent {
  margin-left: v-bind(menuWidth);
}
</style>
